package com.ruoyi.webs.utils.baiduocr;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.json.JSONObject;


public class AuthService {
    public static String getAuth() {
        String clientId = "yqb73aGQjAcPTNgGpk2MtbGv";

        String clientSecret = "yrXatR5q5hFmc8sH2SUHpFWrjLZKSis2";
        return getAuth(clientId, clientSecret);
    }


    public static String getAuth(String ak, String sk) {
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = String.valueOf(authHost) +

                "grant_type=client_credentials" +

                "&client_id=" + ak +

                "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);

            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();

            Map<String, List<String>> map = connection.getHeaderFields();

            for (String key : map.keySet()) {
                System.err.println(String.valueOf(key) + "--->" + map.get(key));
            }

            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result = String.valueOf(result) + line;
            }


            System.err.println("result:" + result);
            JSONObject jsonObject = new JSONObject();
            String access_token = jsonObject.getStr("access_token");
            return access_token;
        } catch (Exception e) {
            System.err.printf("获取token失败！", new Object[0]);
            e.printStackTrace(System.err);

            return null;
        }
    }
}